import { getProfile, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, newtoken) {
    state.token = newtoken
    // 同步到缓存
    setToken(newtoken)
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  },
  setuserInfo(state, newuserInfo) {
    state.userInfo = newuserInfo
  }
}
const actions = {
  // context上下文，传入参数
  async login(context, data) {
    const token = await login(data)

    context.commit('setToken', token)
  },

  async getuserInfo(context) {
    const result = await getProfile()
    context.commit('setuserInfo', result)
  },
  clearuserInfo(context) {
    context.commit('removeToken')
    context.commit('setuserInfo', {})
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
